package com.hzhh123.crypto.handle;

import com.hzhh123.crypto.annotation.CryptoType;
import com.hzhh123.crypto.config.CryptoProperties;
import com.hzhh123.crypto.exception.EncryptException;
import com.hzhh123.crypto.utils.CryptoPropertiesUtils;
import com.hzhh123.crypto.utils.DesUtils;
import com.hzhh123.crypto.utils.RsaUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author hzhh123
 * @version 1.0
 * @date 2022/4/15 16:34
 * @des
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@CryptoType("RSA")
@Component
public class RsaCryptoHandle extends AbstractCrypto {
    private final CryptoProperties cryptoProperties;


    @Override
    public String encrypt(String str) {
        CryptoProperties.PairKey cryptoPropertiesPairKey = getCryptoPropertiesPairKey();
        return RsaUtils.encrypt(str, cryptoPropertiesPairKey.getPublicKey());
    }

    @Override
    public String decrypt(String str) {
        CryptoProperties.PairKey cryptoPropertiesPairKey = getCryptoPropertiesPairKey();
        return RsaUtils.decrypt(str, cryptoPropertiesPairKey.getPrivateKey());
    }

    private CryptoProperties.PairKey getCryptoPropertiesPairKey() {
        CryptoProperties.PairKey cryptoPropertiesPairKey = CryptoPropertiesUtils.getCryptoPropertiesPairKey("RSA", cryptoProperties);
        if (cryptoPropertiesPairKey == null) {
            throw new EncryptException("RSA加解密配置出错");
        }
        if (cryptoPropertiesPairKey.getPublicKey() == null) {
            throw new EncryptException("RSA公钥不能为空");
        }
        if (cryptoPropertiesPairKey.getPrivateKey() == null) {
            throw new EncryptException("RSA私钥不能为空");
        }
        return cryptoPropertiesPairKey;
    }
}
